<!DOCTYPE html>




<html class="theme-next gemini" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
    
  
  <link href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|Source Code Pro:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="https://cdn.staticfile.org/font-awesome/4.6.2/css/font-awesome.css" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=6.0.0" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="icon" type="image/png" sizes="32x32" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="icon" type="image/png" sizes="16x16" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="mask-icon" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0" color="#222">





  <meta name="keywords" content="vps, java, python, golang, springmvc">




  


  <link rel="alternate" href="/atom.xml" title="张恒的网络日志" type="application/atom+xml">






<meta name="keywords" content="java, python, go, 技术, 学习笔记, spring">
<meta property="og:type" content="website">
<meta property="og:title" content="张恒的网络日志">
<meta property="og:url" content="http://blog.gavinzh.com/404.html">
<meta property="og:site_name" content="张恒的网络日志">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-01-05T08:52:36.912Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="张恒的网络日志">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.0.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    fastclick: true,
    lazyload: true,
    tabs: true,
    motion: {"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.gavinzh.com/404.html">





  <title>QEMU-IMG入门教程 | 张恒的网络日志</title>
  




<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-98061925-1', 'auto');
  ga('send', 'pageview');
</script>





</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">张恒的网络日志</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">Zhang Heng's WebSite Blog</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.gavinzh.com/2017/08/02/qemu-img-tutorial-commands/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Gavin Zhang">
      <meta itemprop="description" content>
      <meta itemprop="image" content="https://avatars3.githubusercontent.com/u/5567916">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="张恒的网络日志">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">QEMU-IMG入门教程</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-08-02T06:36:00+00:00">2017-08-02</time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/笔记/" itemprop="url" rel="index">
                    <span itemprop="name">笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2017/08/02/qemu-img-tutorial-commands/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2017/08/02/qemu-img-tutorial-commands/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/2017/08/02/qemu-img-tutorial-commands/" class="leancloud_visitors" data-flag-title="QEMU-IMG入门教程">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>一台虚拟机的核心就是一个磁盘镜像，这个镜像可以理解成虚拟机的磁盘，里面有虚拟机的操作系统和驱动等重要文件，qemu-img就是quemu创建管理磁盘镜像的工具。</p>
<p><img src="/images/pasted-52.png" alt="upload successful"></p>
<a id="more"></a>
<h2 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h2><p>安装好qemu-kvm后就能够使用qemu-img命令。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">yum install -y qemu-kvm</span><br><span class="line">或</span><br><span class="line">apt-get install qemu-kvm</span><br></pre></td></tr></table></figure>

<h2 id="常用命令"><a href="#常用命令" class="headerlink" title="常用命令"></a>常用命令</h2><p>接下来我们走一个真实流程，借此来熟悉了解qemu-img的常用命令</p>
<h3 id="创建磁盘镜像"><a href="#创建磁盘镜像" class="headerlink" title="创建磁盘镜像"></a>创建磁盘镜像</h3><p>命令格式:</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">qemu-img create [-f fmt] [-o options] filename [size]</span><br></pre></td></tr></table></figure>

<p>创建一个格式为fmt大小为size文件名为filename的镜像文件。根据文件格式fmt的不同，还可以添加一个或多个选项（options）来附加对该文件的各种功能设置，可以使用“-o ?”来查询某种格式文件支持那些选项，在“-o”选项中各个选项用逗号来分隔。</p>
<p>如果“-o”选项中使用了backing_file这个选项来指定其后端镜像文件，那么这个创建的镜像文件仅记录与后端镜像文件的差异部分。后端镜像文件不会被修改，除非在QEMU monitor中使用“commit”命令或者使用“qemu-img commit”命令去手动提交这些改动。这种情况下，size参数不是必须需的，其值默认为后端镜像文件的大小。另外，直接使用“-b backfile”参数也与“-o backing_file=backfile”效果相同。</p>
<p>size选项用于指定镜像文件的大小，其默认单位是字节（bytes），也可以支持k（或K）、M、G、T来分别表示KB、MB、GB、TB大小。另外，镜像文件的大小（size）也并非必须写在命令的最后，它也可以被写在“-o”选项中作为其中一个选项。</p>
<p>随后，我们会使用该命令的更多参数，目前我们需要创建一个<code>qcow2</code>格式<code>4GB</code>大小的镜像文件<code>test.img</code>，，命令如下:</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">qemu-img create -f qcow2 test.img 4GB</span><br><span class="line">或</span><br><span class="line">qemu-img create -f qcow2 -o size=4GB test.img</span><br></pre></td></tr></table></figure>

<h2 id="磁盘一致性检查"><a href="#磁盘一致性检查" class="headerlink" title="磁盘一致性检查"></a>磁盘一致性检查</h2><p>命令格式:</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">qemu-img check [-f fmt] filename</span><br></pre></td></tr></table></figure>

<p>对磁盘镜像文件进行一致性检查，查找镜像文件中的错误，目前仅支持对“qcow2”、“qed”、“vdi”格式文件的检查。其中，qcow2是QEMU 0.8.3版本引入的镜像文件格式，也是目前使用最广泛的格式。qed（QEMU enhanced disk）是从QEMU 0.14版开始加入的增强磁盘文件格式，为了避免qcow2格式的一些缺点，也为了提高性能，不过目前还不够成熟。而vdi（Virtual Disk Image）是Oracle的VirtualBox虚拟机中的存储格式。参数-f fmt是指定文件的格式，如果不指定格式qemu-img会自动检测，filename是磁盘镜像文件的名称（包括路径）。</p>
<p>我们需要对刚创建的磁盘镜像文件做一个检查，命令如下:</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">qemu-img check test.img</span><br><span class="line">或</span><br><span class="line">qemu-img check -f qcow2 test.img</span><br></pre></td></tr></table></figure>

<p>结果如下:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">No errors were found on the image.</span><br></pre></td></tr></table></figure>

<h3 id="转换镜像格式"><a href="#转换镜像格式" class="headerlink" title="转换镜像格式"></a>转换镜像格式</h3><p>命令格式:</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">qemu-img convert [-c] [-f fmt] [-O output_fmt] [-o options] filename [filename2 […]] output_filename</span><br></pre></td></tr></table></figure>

<p>将fmt格式的filename镜像文件根据options选项转换为格式为output_fmt的名为output_filename的镜像文件。它支持不同格式的镜像文件之间的转换，比如可以用VMware用的vmdk格式文件转换为qcow2文件，这对从其他虚拟化方案转移到KVM上的用户非常有用。一般来说，输入文件格式fmt由qemu-img工具自动检测到，而输出文件格式output_fmt根据自己需要来指定，默认会被转换为与raw文件格式（且默认使用稀疏文件的方式存储以节省存储空间）。</p>
<p>其中，“-c”参数是对输出的镜像文件进行压缩，不过只有qcow2和qcow格式的镜像文件才支持压缩，而且这种压缩是只读的，如果压缩的扇区被重写，则会被重写为未压缩的数据。同样可以使用“-o options”来指定各种选项，如：后端镜像、文件大小、是否加密等等。使用backing_file选项来指定后端镜像，让生成的文件是copy-on-write的增量文件，这时必须让转换命令中指定的后端镜像与输入文件的后端镜像的内容是相同的，尽管它们各自后端镜像的目录、格式可能不同。</p>
<p>如果使用qcow2、qcow、cow等作为输出文件格式来转换raw格式的镜像文件（非稀疏文件格式），镜像转换还可以起到将镜像文件转化为更小的镜像，因为它可以将空的扇区删除使之在生成的输出文件中并不存在。</p>
<p>我们之前创建了一个<code>qcow2</code>格式大小<code>4G</code>名为<code>test.img</code>的镜像文件，现在，我们想对这个镜像文件做扩容，所以需要先转换为<code>raw</code>格式文件。命令如下:</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">qemu-img convert -O raw test.img test_convert1.raw</span><br></pre></td></tr></table></figure>

<h3 id="查看镜像信息"><a href="#查看镜像信息" class="headerlink" title="查看镜像信息"></a>查看镜像信息</h3><p>命令格式:</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">qemu-img info [-f fmt] filename</span><br></pre></td></tr></table></figure>

<p>展示filename镜像文件的信息。如果文件是使用稀疏文件的存储方式，也会显示出它的本来分配的大小以及实际已占用的磁盘空间大小。如果文件中存放有客户机快照，快照的信息也会被显示出来。下面的命令行演示了前面进行文件转换的输入、输出文件的信息。</p>
<p>我们把<code>qcow2</code>格式文件转成了<code>raw</code>格式文件，接下来看看raw格式文件的信息，命令如下:</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">qemu-img info test_convert1.raw</span><br></pre></td></tr></table></figure>

<p>结果如下:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">image: test_convert1.raw</span><br><span class="line">file format: raw</span><br><span class="line">virtual size: 4.0G (4268709120 bytes)</span><br><span class="line">disk size: 0G</span><br></pre></td></tr></table></figure>

<h3 id="修改镜像大小"><a href="#修改镜像大小" class="headerlink" title="修改镜像大小"></a>修改镜像大小</h3><p>命令格式:</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">qemu-img resize filename [+ | -]size</span><br></pre></td></tr></table></figure>

<p>改变镜像文件的大小，使其不同于创建之时的大小。“+”和“-”分别表示增加和减少镜像文件的大小，而size也是支持K、M、G、T等单位的使用。缩小镜像的大小之前，需要在客户机中保证里面的文件系统有空余空间，否则会数据丢失，另外，qcow2格式文件不支持缩小镜像的操作。在增加了镜像文件大小后，也需启动客户机到里面去应用“fdisk”、“parted”等分区工具进行相应的操作才能真正让客户机使用到增加后的镜像空间。不过使用resize命令时需要小心（最好做好备份），如果失败的话，可能会导致镜像文件无法正常使用而造成数据丢失。</p>
<p>接下来，我们增加1G容量到镜像中，命令如下:</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">qemu-img resize test_convert1.raw +1G</span><br></pre></td></tr></table></figure>

<p>重新查看镜像信息，会发现镜像大小已经改变。</p>
<h3 id="镜像的快照"><a href="#镜像的快照" class="headerlink" title="镜像的快照"></a>镜像的快照</h3><p>命令格式:</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">qemu-img snapshot [-l | -a snapshot | -c snapshot | -d snapshot] filename</span><br></pre></td></tr></table></figure>

<p>“-l” 选项是查询并列出镜像文件中的所有快照，“-a snapshot”是让镜像文件使用某个快照，“-c snapshot”是创建一个快照，“-d”是删除一个快照。</p>
<p>我们为<code>test.img</code>先创建一个名为booting的快照，然后再检查他，最后再删除这个快照，命令如下:</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">qemu-img snapshot -c booting test.img</span><br><span class="line">qemu-img snapshot -l test.img</span><br><span class="line">qemu-img snapshot -d booting test.img</span><br></pre></td></tr></table></figure>

<h3 id="派生镜像"><a href="#派生镜像" class="headerlink" title="派生镜像"></a>派生镜像</h3><p>在创建镜像中，有一个参数<code>backing_file</code>，它可以在一个镜像的基础上创建一个镜像，就像docker技术一样。</p>
<p>我们来根据<code>test.img</code>创建一个派生镜像<code>test_pack1.img</code>,具体操作如下:</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">qemu-img create -f qcow2 test_pack1.img -o backing_file=test.img 4G</span><br><span class="line">或</span><br><span class="line">qemu-img create -f qcow2 test_pack1.img -o backing_file=test.img,size=4G</span><br><span class="line">或</span><br><span class="line">qemu-img create -f qcow2 test_pack1.img -b test.img 4G</span><br></pre></td></tr></table></figure>

<p>结合之前的格式转换，镜像大小修改，我们可以安全的修改一个镜像的大小了。</p>
<h2 id="全部命令"><a href="#全部命令" class="headerlink" title="全部命令"></a>全部命令</h2><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br></pre></td><td class="code"><pre><span class="line">qemu-img version 2.6.0 (qemu-kvm-ev-2.6.0-28.el7.10.1), Copyright (c) 2004-2008 Fabrice Bellard</span><br><span class="line">usage: qemu-img command [command options]</span><br><span class="line">QEMU disk image utility</span><br><span class="line"></span><br><span class="line">Command syntax:</span><br><span class="line">  check [-q] [--object objectdef] [--image-opts] [-f fmt] [--output=ofmt] [-r [leaks | all]] [-T src_cache] filename</span><br><span class="line">  create [-q] [--object objectdef] [--image-opts] [-f fmt] [-o options] filename [size]</span><br><span class="line">  commit [-q] [--object objectdef] [--image-opts] [-f fmt] [-t cache] [-b base] [-d] [-p] filename</span><br><span class="line">  compare [--object objectdef] [--image-opts] [-f fmt] [-F fmt] [-T src_cache] [-p] [-q] [-s] filename1 filename2</span><br><span class="line">  convert [--object objectdef] [--image-opts] [-c] [-p] [-q] [-n] [-f fmt] [-t cache] [-T src_cache] [-O output_fmt] [-o options] [-s snapshot_id_or_name] [-l snapshot_param] [-S sparse_size] filename [filename2 [...]] output_filename</span><br><span class="line">  info [--object objectdef] [--image-opts] [-f fmt] [--output=ofmt] [--backing-chain] filename</span><br><span class="line">  map [--object objectdef] [--image-opts] [-f fmt] [--output=ofmt] filename</span><br><span class="line">  snapshot [--object objectdef] [--image-opts] [-q] [-l | -a snapshot | -c snapshot | -d snapshot] filename</span><br><span class="line">  rebase [--object objectdef] [--image-opts] [-q] [-f fmt] [-t cache] [-T src_cache] [-p] [-u] -b backing_file [-F backing_fmt] filename</span><br><span class="line">  resize [--object objectdef] [--image-opts] [-q] filename [+ | -]size</span><br><span class="line">  amend [--object objectdef] [--image-opts] [-p] [-q] [-f fmt] [-t cache] -o options filename</span><br><span class="line"></span><br><span class="line">Command parameters:</span><br><span class="line">  'filename' is a disk image filename</span><br><span class="line">  'objectdef' is a QEMU user creatable object definition. See the qemu(1)</span><br><span class="line">    manual page for a description of the object properties. The most common</span><br><span class="line">    object type is a 'secret', which is used to supply passwords and/or</span><br><span class="line">    encryption keys.</span><br><span class="line">  'fmt' is the disk image format. It is guessed automatically in most cases</span><br><span class="line">  'cache' is the cache mode used to write the output disk image, the valid</span><br><span class="line">    options are: 'none', 'writeback' (default, except for convert), 'writethrough',</span><br><span class="line">    'directsync' and 'unsafe' (default for convert)</span><br><span class="line">  'src_cache' is the cache mode used to read input disk images, the valid</span><br><span class="line">    options are the same as for the 'cache' option</span><br><span class="line">  'size' is the disk image size in bytes. Optional suffixes</span><br><span class="line">    'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),</span><br><span class="line">    'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P)  are</span><br><span class="line">    supported. 'b' is ignored.</span><br><span class="line">  'output_filename' is the destination disk image filename</span><br><span class="line">  'output_fmt' is the destination format</span><br><span class="line">  'options' is a comma separated list of format specific options in a</span><br><span class="line">    name=value format. Use -o ? for an overview of the options supported by the</span><br><span class="line">    used format</span><br><span class="line">  'snapshot_param' is param used for internal snapshot, format</span><br><span class="line">    is 'snapshot.id=[ID],snapshot.name=[NAME]', or</span><br><span class="line">    '[ID_OR_NAME]'</span><br><span class="line">  'snapshot_id_or_name' is deprecated, use 'snapshot_param'</span><br><span class="line">    instead</span><br><span class="line">  '-c' indicates that target image must be compressed (qcow format only)</span><br><span class="line">  '-u' enables unsafe rebasing. It is assumed that old and new backing file</span><br><span class="line">       match exactly. The image doesn't need a working backing file before</span><br><span class="line">       rebasing in this case (useful for renaming the backing file)</span><br><span class="line">  '-h' with or without a command shows this help and lists the supported formats</span><br><span class="line">  '-p' show progress of command (only certain commands)</span><br><span class="line">  '-q' use Quiet mode - do not print any output (except errors)</span><br><span class="line">  '-S' indicates the consecutive number of bytes (defaults to 4k) that must</span><br><span class="line">       contain only zeros for qemu-img to create a sparse image during</span><br><span class="line">       conversion. If the number of bytes is 0, the source will not be scanned for</span><br><span class="line">       unallocated or zero sectors, and the destination image will always be</span><br><span class="line">       fully allocated</span><br><span class="line">  '--output' takes the format in which the output must be done (human or json)</span><br><span class="line">  '-n' skips the target volume creation (useful if the volume is created</span><br><span class="line">       prior to running qemu-img)</span><br><span class="line"></span><br><span class="line">Parameters to check subcommand:</span><br><span class="line">  '-r' tries to repair any inconsistencies that are found during the check.</span><br><span class="line">       '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all</span><br><span class="line">       kinds of errors, with a higher risk of choosing the wrong fix or</span><br><span class="line">       hiding corruption that has already occurred.</span><br><span class="line"></span><br><span class="line">Parameters to snapshot subcommand:</span><br><span class="line">  'snapshot' is the name of the snapshot to create, apply or delete</span><br><span class="line">  '-a' applies a snapshot (revert disk to saved state)</span><br><span class="line">  '-c' creates a snapshot</span><br><span class="line">  '-d' deletes a snapshot</span><br><span class="line">  '-l' lists all snapshots in the given image</span><br><span class="line"></span><br><span class="line">Parameters to compare subcommand:</span><br><span class="line">  '-f' first image format</span><br><span class="line">  '-F' second image format</span><br><span class="line">  '-s' run in Strict mode - fail on different image size or sector allocation</span><br><span class="line"></span><br><span class="line">Supported formats: cloop tftp null-aio ftp ftps null-co http file blkreplay raw parallels sheepdog vmdk vvfat vhdx vpc https ssh host_cdrom host_device nbd iscsi gluster bochs rbd blkdebug luks vdi qcow quorum qcow2 qed blkverify dmg</span><br></pre></td></tr></table></figure>

<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><ul>
<li><a href="http://blog.csdn.net/bravezhe/article/details/8461386" target="_blank" rel="noopener">使用qemu-img管理虚拟机磁盘镜像</a></li>
<li><a href="http://smilejay.com/2012/08/qemu-img-details/" target="_blank" rel="noopener">QEMU-IMG命令</a></li>
<li><a href="http://qemu-buch.de/de/index.php?title=QEMU-KVM-Buch/_Quickstart" target="_blank" rel="noopener">KVM QEMU快速入门手册</a></li>
</ul>

      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Gavin Zhang
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://blog.gavinzh.com/2017/08/02/qemu-img-tutorial-commands/" title="QEMU-IMG入门教程">http://blog.gavinzh.com/2017/08/02/qemu-img-tutorial-commands/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/虚拟化/" rel="tag"># 虚拟化</a>
          
            <a href="/tags/Qemu/" rel="tag"># Qemu</a>
          
            <a href="/tags/磁盘镜像/" rel="tag"># 磁盘镜像</a>
          
            <a href="/tags/qemu-img/" rel="tag"># qemu-img</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/08/01/use-guava-ratelimiter/" rel="next" title="使用guava提供的ratelimiter令牌桶">
                <i class="fa fa-chevron-left"></i> 使用guava提供的ratelimiter令牌桶
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/08/02/QEMU-IMAGE-INFO/" rel="prev" title="QEMU支持镜像概览">
                QEMU支持镜像概览 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="https://avatars3.githubusercontent.com/u/5567916" alt="Gavin Zhang">
            
              <p class="site-author-name" itemprop="name">Gavin Zhang</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">129</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">158</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/jiangmitiao" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:me at gavinzh.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#安装"><span class="nav-number">1.</span> <span class="nav-text">安装</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#常用命令"><span class="nav-number">2.</span> <span class="nav-text">常用命令</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#创建磁盘镜像"><span class="nav-number">2.1.</span> <span class="nav-text">创建磁盘镜像</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#磁盘一致性检查"><span class="nav-number">3.</span> <span class="nav-text">磁盘一致性检查</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#转换镜像格式"><span class="nav-number">3.1.</span> <span class="nav-text">转换镜像格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#查看镜像信息"><span class="nav-number">3.2.</span> <span class="nav-text">查看镜像信息</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#修改镜像大小"><span class="nav-number">3.3.</span> <span class="nav-text">修改镜像大小</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#镜像的快照"><span class="nav-number">3.4.</span> <span class="nav-text">镜像的快照</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#派生镜像"><span class="nav-number">3.5.</span> <span class="nav-text">派生镜像</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#全部命令"><span class="nav-number">4.</span> <span class="nav-text">全部命令</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参考"><span class="nav-number">5.</span> <span class="nav-text">参考</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2013 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Gavin Zhang</span>

  

  
</div>





<div>
	<a href="http://www.beian.miit.gov.cn/" target="_blank">陕ICP备17010002号-1</a>
</div>





        




  <script type="text/javascript">
    (function() {
      var hm = document.createElement("script");
      hm.src = "//tajs.qq.com/stats?sId=61868582";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1261805793&web_id=1261805793" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>





  



  






  













  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/fastclick/1.0.6/fastclick.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/velocity/2.0.5/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/velocity/2.0.5/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.0"></script>



  


  

    
      <script id="dsq-count-scr" src="https://zhang-hengs-website-blog.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://blog.gavinzh.com/2017/08/02/qemu-img-tutorial-commands/';
          this.page.identifier = '2017/08/02/qemu-img-tutorial-commands/';
          this.page.title = 'QEMU-IMG入门教程';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://zhang-hengs-website-blog.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("EhAMmIXTRGtethTcgYwA9afH-gzGzoHsz", "jzP1TaBhMleAUgPLXyB0h8oQ");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=6.0.0"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=6.0.0"></script>


  

</body>
</html>
